package ci.web.codec;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;

/**
 * 跳转到https请求
 * @author zhh
 */
@ChannelHandler.Sharable
class HttpToHttpsHandler extends SimpleChannelInboundHandler<HttpRequest>{

	private HttpToHttpsHandler() {
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
		String location = "https://"+req.headers().get(HttpHeaderNames.HOST)+req.uri();
		HttpResponse response = new DefaultHttpResponse(req.protocolVersion(), HttpResponseStatus.MOVED_PERMANENTLY);
		response.headers().add(HttpHeaderNames.LOCATION, location);
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}

	public static final ChannelHandler instance = new HttpToHttpsHandler();

}
